package com.jeeplus.modules.api.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.core.service.BaseService;
import com.jeeplus.modules.access.entity.Access;
import com.jeeplus.modules.access.service.AccessService;
import com.jeeplus.modules.api.CacheUtil;
import com.jeeplus.modules.api.utils.AlipayUtils;
import com.jeeplus.modules.api.utils.DingdanxiaUtils;
import com.jeeplus.modules.api.utils.MiaoyouquanUtils;
import com.jeeplus.modules.api.utils.WohuiEntity;
import com.jeeplus.modules.api.utils.WohuiUtils;
import com.jeeplus.modules.api.utils.WxPayUtils;
import com.jeeplus.modules.button.entity.Button;
import com.jeeplus.modules.button.service.ButtonService;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.proxyproduct.service.ProxyProductService;
import com.jeeplus.modules.sys.utils.UserUtils;

import net.oschina.j2cache.CacheProviderHolder;

@Service
public class ApiService extends BaseService {
	@Autowired
	private MemberService memberService;
	@Autowired
	private AccessService accessService;
	@Autowired
	private ButtonService buttonService;
	@Autowired
	private ProxyProductService proxyProductService;

	/**
	 * 判断手机号是否可用
	 * @param phone
	 * @return
	 */
	public synchronized boolean checkPhone(String phone) {
		return "0".equals(memberService.executeGetSql("SELECT COUNT(*) FROM t_member WHERE phone = '"+phone+"'").toString());
	}

	/**
	 * 获取入口图片
	 * @return
	 */
	public List<Access> findAccessList() {
		@SuppressWarnings("unchecked")
		List<Access> accessList = (List<Access>) CacheUtils.get(CacheUtil.APP_CACHE, CacheUtil.CACHE_ACCESS_LIST);
		if (accessList == null) {
			accessList = accessService.findList(new Access());
			CacheUtils.put(CacheUtil.APP_CACHE, CacheUtil.CACHE_ACCESS_LIST, accessList);
		}
		return accessList;
	}

	/**
	 * 获取首页接口推荐商品列表
	 * @return
	 */
	public JSONArray findIndexRecommendList() {
		JSONArray recommendList = (JSONArray) CacheProviderHolder.getLevel2Cache(CacheUtil.APP_CACHE).get(CacheUtil.CACHE_RECOMMEND_LIST);
		if (recommendList == null) {
			Map<String, String> params = Maps.newHashMap();
			params.put("page_no", "1");// 第几页，默认：１
			params.put("page_size", "10");// 页大小，默认20，1~100
			params.put("sort", "new");// 按照人气值从高到低进行排序
			JSONObject result = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_quantian, params);
			logger.debug("折淘客返回数据：" + result.toString());
			if ("200".equals(result.getString("status"))) {
				recommendList = result.getJSONArray("content");
				if (recommendList != null && !recommendList.isEmpty()) {
					for (int i = 0; i < recommendList.size(); i++) {
						JSONObject o = recommendList.getJSONObject(i);
						if (StringUtils.isNotBlank(o.getString("small_images"))) {
							recommendList.remove(i);
						}
					}
				}
				if (recommendList != null) {
					CacheProviderHolder.getLevel2Cache(CacheUtil.APP_CACHE).put(CacheUtil.CACHE_RECOMMEND_LIST, recommendList, 3600);// 缓存1小时
				}
			}
		}
		return recommendList;
	}
	/**
	 * 获取按钮图标列表
	 * @return
	 */
	public List<Button> findButtonList() {
		@SuppressWarnings("unchecked")
		List<Button> buttonList = (List<Button>) CacheUtils.get(CacheUtil.APP_CACHE, CacheUtil.CACHE_BUTTON_LIST);
		if (buttonList == null) {
			buttonList = buttonService.findList(new Button());
			CacheUtils.put(CacheUtil.APP_CACHE, CacheUtil.CACHE_BUTTON_LIST, buttonList);
		}
		return buttonList;
	}

	/**
	 *  查询首页淘客一分类
	 * @return
	 */
	public List<Map<String, Object>> findAmoyCategory() {
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> dataList = (List<Map<String, Object>>) CacheProviderHolder.getLevel2Cache(CacheUtil.APP_CACHE).get(CacheUtil.CACHE_TB_CATEGORY_LIST);
		if (dataList == null) {
			dataList = Lists.newArrayList();
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.api_type, Maps.newHashMap());
			logger.debug("折淘客返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("status"))) {
				JSONArray dataArray = jsonObject.getJSONArray("type");
				if (dataArray != null) {
					for (int i = 0; i < dataArray.size(); i++) {
						JSONObject c = dataArray.getJSONObject(i);
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("id", c.get("cid"));
						map.put("name", c.get("name"));
						map.put("icon", c.get("q_pic"));
						dataList.add(map);
					}
				}
				CacheProviderHolder.getLevel2Cache(CacheUtil.APP_CACHE).put(CacheUtil.CACHE_TB_CATEGORY_LIST, dataList, 86400);// 缓存24小时
			}
		}
		return dataList;
	}
	
	/**
	 * 淘客代理商品查询，用于判断是否被代理
	 * @param productId
	 * @param province
	 * @param city
	 * @param area
	 * @return
	 */
	public String getProxyProductCountByProductId(String productId, String type, String province, String city, String area) {
		return proxyProductService.executeGetSql("SELECT COUNT(a.id) FROM t_proxy_product a JOIN t_proxy_order b ON a.`code` = b.`code` WHERE a.product_id = '"+productId+"' AND a.type = '"+type+"' AND b.province = '"+province+"' AND b.city = '"+city+"' AND b.area = '"+area+"' AND (b.state = '0' OR b.state = '1')").toString();
	}
	
	/**
	 * 退款
	 * @param out_trade_no 支付单号
	 * @param amount 退款金额
	 * @param totalFee 订单总额 （微信用）
	 * @param type 支付方式 1支付宝 2微信 3平台购物券 4商城购物券
	 */
	public void refund(String out_trade_no, String amount, String totalFee, String type,String trade_type) {
		// 1支付宝 2微信 3平台券 4商城券
		if ("1".equals(type)) {
			String out_request_no="0";
			BigDecimal a = new BigDecimal(amount);
			BigDecimal b=new BigDecimal(totalFee);
			if(a.compareTo(b) == -1){//a小于b
				out_request_no ="1";
			}
			AlipayUtils.refund(out_trade_no, amount,out_request_no);
		} else if ("2".equals(type)) {
			totalFee = new BigDecimal(totalFee).multiply(new BigDecimal("100")).intValue() + "";
			amount = new BigDecimal(amount).multiply(new BigDecimal("100")).intValue() + "";
			WxPayUtils.refund(out_trade_no, null, totalFee, amount,trade_type);
		} else if ("3".equals(type) || "4".equals(type)) {
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("OrderNO", out_trade_no));
			list.add(new WohuiEntity("Money", amount));
			JSONObject object = WohuiUtils.send(WohuiUtils.WHKPayRefund, list);
			if (!"0000".equals(object.getString("respCode"))) {
				logger.error("我惠卡退款失败：" + object.getString("respMsg"));
			}
		}
	}
	
	/**
	 * 订单支付-我惠会员系统
	 * @param OrderNO 订单号
	 * @param CardGUID 用户ID
	 * @param Province 省份
	 * @param City 城市
	 * @param District 区县
	 * @param GoodsID 商品ID（多个用","分隔）
	 * @param GoodsName 商品名称
	 * @param GYSCode 供应商编码
	 * @param BuyNum 数量
	 * @param Money 订单金额
	 * @param XFQ 消费券冲抵金额
	 * @param ZSQ 专属券冲抵金额
	 * @param PTFL 铜板
	 * @param HYFL 会员返利 (会员返利，除了商圈默认为零)
	 * @param PayTime 支付时间
	 * @param ImportTime 导入时间
	 * @param Source 来源（YD 云店、ALI 阿里、JD 京东、PDD 拼多多，YD_YHQ 云店-优惠券、CX_JP 机票、CX_JD 酒店、CX_HCP 火车票，CX_XYK 信用卡）
	 * @param Diff 差额
	 * @param Total 订单总金额
	 * @returnD
	 */

	public JSONObject orderPay(String BuyNum , String OrderNO, String CardGUID, String Province, String City, String District, String GYSCode, String Money, String PTFL,String HYFL, String PayTime, String ImportTime,  String Source, String GoodsID, String Area, String TZBT, String DLBT,String GoodsName ,String Diff,String Total,String XFQ,String ZSQ) {
		List<WohuiEntity> entityList = Lists.newArrayList();
		if(StringUtils.isBlank(Province)){
			Province= "";
		}
		if(StringUtils.isBlank(City)){
			City= "";
		}
		if(StringUtils.isBlank(District)){
			District= "";
		}
		if(StringUtils.isBlank(XFQ)){
			XFQ= "0";
		}
		if(StringUtils.isBlank(ZSQ)){
			ZSQ= "0";
		}
		entityList.add(new WohuiEntity("OrderNO", OrderNO));
		entityList.add(new WohuiEntity("CardGUID", CardGUID));
		entityList.add(new WohuiEntity("Province", Province));
		entityList.add(new WohuiEntity("City", City));
		entityList.add(new WohuiEntity("District", District, false));
		entityList.add(new WohuiEntity("GoodsID", GoodsID));
		entityList.add(new WohuiEntity("GoodsName", GoodsName, false));
		entityList.add(new WohuiEntity("GYSCode", GYSCode));
		entityList.add(new WohuiEntity("BuyNum", BuyNum));
		entityList.add(new WohuiEntity("Total", Total));
		entityList.add(new WohuiEntity("Money", Money));
		entityList.add(new WohuiEntity("XFQ", XFQ));
		entityList.add(new WohuiEntity("ZSQ", ZSQ));
		entityList.add(new WohuiEntity("PTFL", PTFL));
		entityList.add(new WohuiEntity("HYFL", HYFL));
		entityList.add(new WohuiEntity("ImportTime", ImportTime));
		entityList.add(new WohuiEntity("PayTime", PayTime));
		entityList.add(new WohuiEntity("Source", Source));
		entityList.add(new WohuiEntity("Area", Area));
		entityList.add(new WohuiEntity("Diff", Diff));
		return WohuiUtils.send(WohuiUtils.OrderPay, entityList);
	}
	/**
	 * 订单-已结算 我惠会员系统
	 * @param OrderNO
	 * @param Money
	 * @param PTFL
	 * @return
	 */
	public JSONObject orderSettle(String OrderNO, String Money, String PTFL) {
		List<WohuiEntity> entityList = Lists.newArrayList();
		entityList.add(new WohuiEntity("OrderNO", OrderNO));
		entityList.add(new WohuiEntity("Money", Money));
		entityList.add(new WohuiEntity("PTFL", PTFL));
		return WohuiUtils.send(WohuiUtils.OrderSettle, entityList);
	}
	
	/**
	 * 订单-已失效 我惠会员系统
	 * @param OrderNO
	 * @return
	 */
	public JSONObject orderInvalid(String OrderNO) {
		List<WohuiEntity> entityList = Lists.newArrayList();
		entityList.add(new WohuiEntity("OrderNO", OrderNO));
		return WohuiUtils.send(WohuiUtils.OrderInvalid, entityList);
	}
	/**
	 * 联盟订单支付-我惠会员系统
	 * @param OrderNO 订单号
	 * @param CardGUID 用户ID
	 * @param Province 省份
	 * @param City 城市
	 * @param District 区县
	 * @param GoodsID 商品ID（多个用","分隔）
	 * @param GoodsName 商品名称
	 * @param BuyNum 数量
	 * @param Money 订单金额
	 * @param PTFL 铜板
	 * @param ImportTime 导入时间
	 * @param PayTime 支付时间
	 * @param Source 来源（YD 云店、ALI 阿里、JD 京东、PDD 拼多多，YD_YHQ 云店-优惠券、CX_JP 机票、CX_JD 酒店、CX_HCP 火车票，CX_XYK 信用卡）
	 * @returnD
	 */

	public JSONObject UnionOrderPay(String BuyNum , String OrderNO, String CardGUID, String Province, String City, String District,  String Money, String PTFL, String PayTime, String ImportTime, String Source,  String GoodsID,String GoodsName) {
		List<WohuiEntity> entityList = Lists.newArrayList();
		if(StringUtils.isBlank(Province)){
			Province= "";
		}
		if(StringUtils.isBlank(City)){
			City= "";
		}
		if(StringUtils.isBlank(District)){
			District= "";
		}
		entityList.add(new WohuiEntity("OrderNO", OrderNO));
		entityList.add(new WohuiEntity("CardGUID", CardGUID));
		entityList.add(new WohuiEntity("Province", Province));
		entityList.add(new WohuiEntity("City", City));
		entityList.add(new WohuiEntity("District", District, false));
		entityList.add(new WohuiEntity("GoodsID", GoodsID));
		entityList.add(new WohuiEntity("GoodsName", GoodsName, false));
		entityList.add(new WohuiEntity("BuyNum", BuyNum));
		entityList.add(new WohuiEntity("Money", Money));
		entityList.add(new WohuiEntity("PTFL", PTFL));
		entityList.add(new WohuiEntity("ImportTime", ImportTime));
		entityList.add(new WohuiEntity("PayTime", PayTime));
		entityList.add(new WohuiEntity("Source", Source));
		return WohuiUtils.send(WohuiUtils.UnionOrderPay, entityList);
	}

	/**
	 * 联盟订单-订单-已结算 我惠会员系统
	 * @param OrderNO
	 * @param Money
	 * @param PTFL
	 * @return
	 */
	public JSONObject UnionOrderSettle(String OrderNO, String Money, String PTFL) {
		List<WohuiEntity> entityList = Lists.newArrayList();
		entityList.add(new WohuiEntity("OrderNO", OrderNO));
		entityList.add(new WohuiEntity("Money", Money));
		entityList.add(new WohuiEntity("PTFL", PTFL));
		return WohuiUtils.send(WohuiUtils.UnionOrderSettle, entityList);
	}

	/**
	 * 联盟订单-订单-已失效 我惠会员系统
	 * @param OrderNO
	 * @return
	 */
	public JSONObject UnionOrderInvalid(String OrderNO) {
		List<WohuiEntity> entityList = Lists.newArrayList();
		entityList.add(new WohuiEntity("OrderNO", OrderNO));
		return WohuiUtils.send(WohuiUtils.UnionOrderInvalid, entityList);
	}
}
